/**
 * @(#)DataElementConverter.java Jan 7, 2010
 *   
 * Copyright  (c) 2009-2010 Wilmar IT Service,  Inc.   
 * All  rights  reserved.   
 * TODO
 */

package com.wilmar.process.web.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.wilmar.process.core.ProcessSystemDeclareKeys;

/**
 * 时间类型转换器，可以将系统定义的（长日期 长时间）与（长日期）格式转换成java.util.Date对象
 * 
 * @author makubex Email:makubexnet@gmail.com
 * @version 1.0.0
 */
public class DataElementConverter extends StrutsTypeConverter {

	public static final DateFormat[] ACCEPT_DATE_FORMATS = {
			new SimpleDateFormat(
					ProcessSystemDeclareKeys.SYSTEM_LONG_DATE_FORMAT
							+ ProcessSystemDeclareKeys.SPACE
							+ ProcessSystemDeclareKeys.SYSTEM_LONG_TIME_FORMAT),
			new SimpleDateFormat(
					ProcessSystemDeclareKeys.SYSTEM_LONG_DATE_FORMAT) };

	/**
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertFromString(java.util.Map,
	 *      java.lang.String[], java.lang.Class)
	 */
	public Object convertFromString(@SuppressWarnings("rawtypes") Map context, String[] value, @SuppressWarnings("rawtypes") Class toType) {
		if (value[0] == null || value[0].trim().equals(""))
			return null;
		if (toType == Date.class) {
			for (DateFormat format : ACCEPT_DATE_FORMATS) {
				try {
					return format.parse(value[0]);
				} catch (ParseException e) {
					continue;
				} catch (RuntimeException e) {
					continue;
				}
			}
		}
		return null;
	}

	/**
	 * 
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertToString(java.util
	 *      .Map, java.lang.Object)
	 */
	public String convertToString(@SuppressWarnings("rawtypes") Map arg0, Object o) {
		if (o instanceof Date) {
			SimpleDateFormat sdf = new SimpleDateFormat(
					ProcessSystemDeclareKeys.SYSTEM_LONG_DATE_FORMAT
							+ ProcessSystemDeclareKeys.SPACE
							+ ProcessSystemDeclareKeys.SYSTEM_LONG_TIME_FORMAT);
			try {
				return sdf.format((Date) o);
			} catch (RuntimeException e) {
				return "";
			}
		}
		return "";
	}

}
